package com.test.qpbgboot.user.controller;

import com.test.qpbgboot.base.response.JsonResult;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.service.SMSService;
import com.test.qpbgboot.base.utils.JwtTokenUtils;
import com.test.qpbgboot.user.pojo.dto.*;
import com.test.qpbgboot.user.pojo.vo.UserFansVO;
import com.test.qpbgboot.user.pojo.vo.UserFollowingVO;
import com.test.qpbgboot.user.pojo.vo.UserVO;
import com.test.qpbgboot.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/v1/user")
@Slf4j
@Api(tags = "user module")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SMSService smsService;

    @PostMapping("/reg")
    @ApiOperation(value = "用户注册")
    public JsonResult reg(@Valid @RequestBody UserRegParam userRegParam) {
        log.debug("用户注册:userRegParam={}", userRegParam);
        userService.reg(userRegParam);
        return JsonResult.success();
    }

    @GetMapping("/captcha/generate/{phone}")
    @ApiOperation(value = "验证码发送")
    public JsonResult generateCaptcha(
            @PathVariable
            @ApiParam(value = "手机号", name = "phone", required = true)
            String phone) {
        log.debug("验证码发送:phone={}", phone);
        if (!phone.matches("^[0-9]{11}$")) {
            return new JsonResult(ResultStatus.INCORRECT_FORMAT);
        }
        smsService.sendNewCaptcha(phone);
        return JsonResult.success();
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public ResponseEntity<JsonResult> login(
            @Valid @RequestBody UserLoginParam userLoginParam) {
        log.debug("用户登录:userLoginParam={}", userLoginParam);
        UserVO userVO = userService.login(userLoginParam);
        return ResponseEntity.ok()
                .header("Authorization","Bearer " +
                        JwtTokenUtils.createJWT(userVO, 180))
                .body(JsonResult.success(userVO));
    }

//    @PostMapping("/login/wechat")
//    @ApiOperation(value = "用户微信登录")
//    public ResponseEntity<JsonResult> wechatLogin(
//            @RequestParam
//            @ApiParam(value = "微信编码", name = "code", required = true)
//            String code) {
//        log.debug("用户微信登录:code={}", code);
//        UserVO userVO = userService.wechatLogin(code);
//        return ResponseEntity.ok()
//                .header("Authorization", "Bearer " +
//                        JwtTokenUtils.createJWT(userVO, 30))
//                .body(JsonResult.success(userVO));
//    }

    @PostMapping("/login/phone")
    @ApiOperation(value = "用户手机号登录")
    public ResponseEntity<JsonResult> phoneLogin(
            @Valid @RequestBody PhoneLoginParam phoneLoginParam) {
        log.debug("用户手机号登录:phoneLoginParam={}", phoneLoginParam);
        UserVO userVO = userService.phoneLogin(phoneLoginParam);
        return ResponseEntity.ok()
                .header("Authorization", "Bearer " +
                        JwtTokenUtils.createJWT(userVO, 30))
                .body(JsonResult.success(userVO));
    }

    @PostMapping("/password")
    @ApiOperation(value = "用户密码修改")
    public JsonResult password(
            @Valid @RequestBody
            UserPasswordParam userPasswordParam,
            @ApiIgnore
            @RequestHeader("Authorization")
            String token) {
        log.debug("用户密码修改:userPasswordParam={}", userPasswordParam);
        UserService.checkUserVOId(token, userPasswordParam.getId());
        userService.passwordChange(userPasswordParam);
        return JsonResult.success();
    }

    @PostMapping("/log-off/{userId}")
    @ApiOperation(value = "用户注销")
    public JsonResult logOff(
            @PathVariable
            @ApiParam(value = "用户id", name = "userId", required = true)
            Long userId,
            @ApiIgnore @RequestHeader("Authorization")
            String token) {
        log.debug("用户注销:userId={}", userId);
        UserService.checkUserVOId(token, userId);
        userService.userLogOff(userId);
        return JsonResult.success();
    }

    @PostMapping("/save")
    @ApiOperation(value = "用户基本信息保存")
    public JsonResult save(
            @Valid @RequestBody
            UserSaveParam userSaveParam) {
        log.debug("用户基本信息保存:userSaveParam={}", userSaveParam);
//        BaseUtils.removeBlank(userSaveParam);
//        UserService.checkUserVOId(token, userSaveParam.getId());
        userService.userSave(userSaveParam);
        return JsonResult.success();
    }

    @GetMapping("/select/{userId}")
    @ApiOperation(value = "用户基本信息查询")
    public JsonResult select(
            @PathVariable
            @ApiParam(value = "用户id", name = "userId", required = true)
            Long userId) {
        log.debug("用户基本信息查询:userId={}", userId);
        UserVO userVO = userService.userSelect(userId);
        return JsonResult.success(userVO);
    }

    @PostMapping("/follow")
    @ApiOperation(value = "用户关注")
    public JsonResult follow(
            @Valid
            @RequestBody
            UserFollowParam userFollowParam,
            @ApiIgnore @RequestHeader("Authorization")
            String token) {
        log.debug("用户关注:userFollowParam={}", userFollowParam);
        UserService.checkUserVOId(token, userFollowParam.getId());
        userService.userFollow(userFollowParam);
        return JsonResult.success();
    }

    @PostMapping("/unfollow")
    @ApiOperation(value = "用户取消关注")
    public JsonResult unfollow(
            @Valid
            @RequestBody
            UserFollowParam userFollowParam) {
        log.debug("用户取消关注:userFollowParam={}", userFollowParam);
        userService.userUnfollow(userFollowParam);
        return JsonResult.success();
    }

    @GetMapping("/following/select/{userId}")
    @ApiOperation(value = "关注对象查询")
    public JsonResult selectFollowing(
            @PathVariable
            @ApiParam(value = "用户id", name = "userId", required = true)
            Long userId) {
        log.debug("关注对象查询:userId={}", userId);
        List<UserFollowingVO> followingList = userService.followingSelect(userId);
        return JsonResult.success(followingList);
    }

    @GetMapping("/fans/select/{userId}")
    @ApiOperation(value = "粉丝用户查询")
    public JsonResult selectFans(
            @PathVariable
            @ApiParam(value = "用户id", name = "userId", required = true)
            Long userId) {
        log.debug("粉丝用户查询:userId={}", userId);
        List<UserFansVO> fansList = userService.fansSelect(userId);
        return JsonResult.success(fansList);
    }



    // 微信公众号接入验证
    @GetMapping("/wx/check")
    public String check(
            @RequestParam(value ="signature")String signature,
            @RequestParam(value ="timestamp")String timestamp,
            @RequestParam(value ="nonce")String nonce,
            @RequestParam(value ="echostr")String echostr
    ){
        boolean check = userService.wxCheck(signature,timestamp,nonce,echostr);
        return check ? echostr : "";
    }

    /**
     * 获取微信二维码
     * @return 包含state和qrCode的响应
     * @throws IOException 当生成二维码失败时抛出
     */
    @GetMapping("/api/wechat/getQrCode")
    public ResponseEntity<Map<String, String>> getQrCode() throws IOException {
        Map<String, String> response = userService.getQrCode();
        return ResponseEntity.ok(response);
    }

    /**
     * 微信授权回调
     * @param code 微信返回的授权码
     * @param state 之前生成的状态标识
     * @param response HTTP响应对象
     * @throws IOException 当处理过程中发生I/O错误时抛出
     */
    @GetMapping(value = "/redirect")
    public void redirect(
            @RequestParam("code") String code,
            @RequestParam("state") String state,
            HttpServletResponse response) throws IOException {
        userService.redirect(code, state, response);
    }

    /**
     * 检查微信登录状态
     * @param state 状态标识
     * @return 包含登录状态和token的响应
     */
    @GetMapping("/api/wechat/check-login")
    public ResponseEntity<Map<String, Object>> checkLogin(@RequestParam String state) {
        Map<String, Object> response = userService.checkLogin(state);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/api/wechat/getUserInfoByWxOpenId")
    public ResponseEntity<JsonResult> getUserInfoByWxOpenId(
            @RequestParam("token") String token) {
        UserVO userVO = userService.getUserInfoByWxOpenId(token);
        System.out.println("userVO = " + userVO);
        return ResponseEntity.ok()
                .header("Authorization", "Bearer " +
                        JwtTokenUtils.createJWT(userVO, 30))
                .body(JsonResult.success(userVO));
    }
}
